//Initializations
var xml=loadXMLDocXP("guncase.xml");
var xsl=loadXMLDocXP("guncase.xsl");

// specifies the element where the xpath is defined
var elemXPath;// value set in updateXSLHeadersC




// uses AJAX to load XML DOM.
function loadXMLDocXP(dname)
{	
	if (window.XMLHttpRequest)
	{
		xhttp=new XMLHttpRequest();
	}
	else
	{

		xhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	xhttp.open("GET",dname,false);
	xhttp.send("");
	return xhttp.responseXML;	
}

//Finds the number of children of the root element in the XML Node Tree
function getXMLLengthXP() {
	var rootIndex = getXMLRootXP()
	if(rootIndex == "Root Element Missing From XML"){
		alert(rootIndex);
	} else{
		//Field value = number of children of the root element
		document.getElementById("size").innerHTML = xml.childNodes[rootIndex].childNodes.length;
	}
}

//Returns the index of the root element in the XML Node Tree.
function getXMLRootXP() {
    var i = 0;

    for (i = 0; i < xml.childNodes.length; i++) {
		//Node type = 1 means the node is an element.  The XML should contain only one root element.
        if (xml.childNodes[i].nodeType == 1) {
             return i;
        }
    }
    return "Root Element Missing From XML";
}
//returns a defined path for the root and its child
function getPathXP()
{
	var rootIndex = getXMLRootXP()
	var rootName=xml.childNodes[rootIndex].nodeName
	var name=xml.childNodes[rootIndex].childNodes[0].nodeName
	path = "/" + rootName + "/" + name;
}
//finds distinct elements and attributes
function getXMLHeadersXP()
{
	//initialize variables and arrays
	var rootIndex = getXMLRootXP()
	var count1 = 0;
	var count2 = 0;
	var header = new Array();
	var attrib = new Array();
	//pull number of rows from hidden element
	var length=getSizeC();
	//loop through xml file rows
	for (var j=0;j<length;j++)
	{
		//finds node of child of root
		var element=xml.childNodes[rootIndex].childNodes[j];
		//all the column nodes
		var row=element.childNodes;
		//first column node
		var column=element.firstChild;
		// loop through headers and record in array
		for (var i=0;i<row.length;i++)
		{
			header[count2]=column.nodeName;
			column=column.nextSibling;
			count2++
		}
		// Attribute node list
		var attribList=element.attributes
		// loop through attributes and record in array
		for (var k=0; k<attribList.length; k++)
		{
		attrib[count1] = attribList.item(k).nodeName;
		count1++
		}
	}
	// joins both arrays and removes duplicates puts info in global variable
	var headerArray = checkDuplicates(header.concat(attrib));
	return headerArray;
}

//removes duplicates from passed array
function checkDuplicates(array) 
{
	var set = {};
	for (var i = 0; i < array.length; i++)
	{
		set[array[i]] = true;
	}
	array = [];
	for (var value in set)
	{
		array.push(value);
	}
	return array;
}

